import router from "@/router/index.js";
import axios, {Axios} from "axios";
import {ElMessage} from "element-plus";

const httpInstance = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000  // 增加超时时间到10秒，避免支付接口超时
})


//request拦截器; 用于请求前的处理
httpInstance.interceptors.request.use(config =>{
    console.log('Request URL:',config.baseURL + config.url);

    // 如果不是 FormData，才设置 Content-Type
    if (!(config.data instanceof FormData)) {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
    }

    return config
},error => {
    return Promise.reject(error)
});

//response响应拦截器; 用于接口响应后的处理
httpInstance.interceptors.response.use(
    response=>{
        let res = response.data;
        //文件
        if(response.config.responseType === 'blob'){
            return res;
        }
        //字符串
        if(response.config.responseType === 'string'){
            res = res ?JSON.parse(res):res
        }
        //当权限不通过时给出提示
        if(res.code === '401'){
            ElMessage.error(res.error)
            router.push("/login")
        }
        return res;
    },
      error => {
        console.error("err:", error); // Use console.error for better visibility

        // Log the detailed error response from the server if it exists
        if (error.response) {
          console.error("Error Response Data:", error.response.data);
        }

        // Network error handling
        if (error.message === 'Network Error') {
            console.error('网络连接失败，请检查网络状态')
            ElMessage.error('网络连接失败，请检查网络连接')
        } else if (error.code === 'ECONNABORTED') {
            console.error('请求超时')
            ElMessage.error('请求超时，请稍后重试')
        }

        return Promise.reject(error);
    }
)

export default httpInstance


